package com.xing.reggie.interceptor;


import com.alibaba.fastjson.JSON;
import com.xing.reggie.common.BaseContext;
import com.xing.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进行登录拦截");
        //获取session
        HttpSession session = request.getSession();
        //后台登录员工session
        Long employee = (Long) session.getAttribute("employee");
        //前台登录用户session
        Long user = (Long) session.getAttribute("user");

        //1.判断是否存在员工session对象
        if (employee != null) {

            //利用线程工具类setId
            BaseContext.setCurrentId(employee);

            return true;
        }
        //2.判断是否存在用户session对象
        if (user != null) {
            //利用线程工具类setId
            BaseContext.setCurrentId(user);
            return true;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
//        else {
//                response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
//                return false;
//            }




    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
